package com.example.config;

import lombok.Data;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import javax.annotation.PostConstruct;

/**
 * <h1>文件通用属性配置类</h1>
 * Created by hanqf on 2021/7/29 10:15.
 */

@Data
@Configuration
@ConfigurationProperties(
        prefix = "spring.servlet.multipart",
        ignoreUnknownFields = true
)
public class FileConfig {

    public static Long FILE_MAX_SIZE;
    public static String ALLOW_FILE_SUFFIXES;
    /**
     * 上传文件的最大值
     */
    private DataSize maxFileSize = DataSize.ofMegabytes(50L);
    /**
     * 允许上传的文件类型
     */
    @Value("${oss.allow_file_suffixes:all}")
    private String allow_file_suffixes;

    /**
     * 验证文件后缀是否合法
     */
    public static boolean isSuffixesOK(String suffix) {
        String[] suffixes = ALLOW_FILE_SUFFIXES.split(",");
        return isSuffixesOK(suffix, suffixes);
    }

    /**
     * 验证文件后缀是否合法
     */
    public static boolean isSuffixesOK(String suffix,String[] suffixes) {
        if (suffixes.length == 1 && "all".equals(suffixes[0])) {
            return true;
        }else {
            if (ArrayUtils.contains(suffixes, suffix.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        FILE_MAX_SIZE = maxFileSize.toBytes();
        ALLOW_FILE_SUFFIXES = allow_file_suffixes;
    }


}
